package com.runa.monitor.platinterface.mqtt;


import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.constants.ResultConstants;
import com.runa.monitor.comm.dto.newComm.*;
import com.runa.monitor.comm.entity.*;
import com.runa.monitor.platinterface.extend.hdb.CollectionUtil;
import com.runa.monitor.platinterface.extend.nb.vo.buildmeter.BuildMeterDecode;
import com.runa.monitor.platinterface.extend.nb.vo.buildmeter.MqttBuildMeterDataVo;
import com.runa.monitor.platinterface.extend.third.pojo.TemperaturePressureCurrentData;
import com.runa.monitor.platinterface.mqtt.vo.*;
import com.runa.monitor.platinterface.netservice.equipment.dtu.fourG.FourGValveDtuService;
import com.runa.monitor.platinterface.platService.RepositoryService;
import com.runa.monitor.platinterface.service.FourGSendService;
import com.runa.persistence.DateUtil;
import com.runa.persistence.StringUtil;
import com.runa.persistence.repository.CommCheckRepository;
import com.runa.persistence.repository.CommMeterRepository;
import com.runa.persistence.repository.CommTemperaturepressureRepository;
import com.runa.persistence.util.LogUtil;
import com.runa.protocol.dto.ModbusResponseData;
import com.runa.protocol.enums.ModbusFunctionCode;
import com.runa.protocol.enums.ModbusType;
import com.runa.protocol.util.ByteUtil;
import com.runa.protocol.util.DigitalUtil;
import com.runa.rccprotocol.analysis.RunaEquDataAnalysis;
import com.runa.rccprotocol.netservice.dtu.ModbusRtuResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Service
public class RUEquService {
    @Resource
    private FourGSendService fourGSendService;

    @Resource
    private RepositoryService repositoryService;
    @Resource
    private FourGValveDtuService fourGValveDtuService;
    @Resource
    private CommMeterRepository commMeterRepository;
    @Resource
    private CommTemperaturepressureRepository commTemperaturepressureRepository;
    @Resource
    private CommCheckRepository commCheckRepository;

    public void executeModbus(String topic, String s) {
        String[] split = topic.split("/");
        if (split.length == 4 && "RU-VC-05".equals(split[1])) {
            String serialNo = split[2];
            String function = split[3];

            byte[] bytes = ByteUtil.hexStringToByte(s);
            if (bytes.length < 7) {
                log.error("4G阀收到modbus错误报文: {} {}", topic, s);
                return;
            }
            int slaveId = bytes[0] & 0xff;
            int functionCode = bytes[1] & 0xff;
            ModbusFunctionCode modbusFunctionCode = ModbusFunctionCode.getByCode(functionCode);
            ModbusRtuResponse modbusRtuResponse = new ModbusRtuResponse(serialNo);
            switch(modbusFunctionCode) {
                case READ_HOLDING_REGISTERS:
                    int count = bytes[2] & 0xff;
                    byte[] slice = ByteUtil.slice(bytes, 3, count);
                    log.debug("{} READ_HOLDING_REGISTERS count: {} slice: {}", serialNo, count, ByteUtil.byteToHexString(slice));
                    ModbusResponseData modbusResponse = new ModbusResponseData(ModbusType.MODBUS_RTU, slaveId, modbusFunctionCode, count, slice);
                    modbusRtuResponse.setModbusResponse(modbusResponse);
                    break;
                case WRITE_REGISTERS:
                    int registerCount = (bytes[4] << 8 & 0xff) + (bytes[5] & 0xff);
                    modbusRtuResponse.setModbusResponse(new ModbusResponseData(ModbusType.MODBUS_RTU, slaveId, modbusFunctionCode, registerCount*2, null));
            }

            log.debug("{} modbusRtuResponse: {} {}", serialNo, JSON.toJSONString(modbusRtuResponse), ByteUtil.byteToHexString(modbusRtuResponse.getModbusResponse().getData()));
            fourGValveDtuService.receive(modbusRtuResponse);

        }
    }

    public void execute(String topic, String json) {
        try {
            if (topic.startsWith("/RU-STC-BT1")) {
                executePanel(json);
            } else if (topic.startsWith("/RU-LRTU-01")) {
                executeTempPressure(topic, json);
            } else {
                executeValveAndMeter(topic, json);
            }
        } catch (Exception e) {
            log.error("{} {} ", topic, json, e);
        }
    }

    private void executeCheck(String topic, String s) {
        log.info("收到4G稽查: {} {}", topic, s);
        FourGCheckVO fourGCheckVO = FourGCheckVO.gene(s);
        String downTopic = topic.replaceAll("up", "down");

        CommCheck commCheck = commCheckRepository.findOne(Example.of(CommCheck.builder()
                .serial(fourGCheckVO.getId()).build())).orElse(null);
        if (null == commCheck) {
            fourGSendService.sendRtcCommand(downTopic);
            return;
        }
        boolean heatingPeriod = DateUtil.heatingPeriod(fourGCheckVO.getHot());
        // todo 下发稽查周期和采集周期
        fourGSendService.sendCommand(commCheck.getId(), downTopic, heatingPeriod
                , fourGCheckVO.getUitv1(), fourGCheckVO.getUitv2(), fourGCheckVO.getCitv1(), fourGCheckVO.getCitv2(), false);

        String upTopic = CheckVO.TOPIC;
        CheckVO checkVO = fourGCheckVO.getCheckVO();
        AsynResult asynResult = AsynResult.success();
        asynResult.setTimestamp(new Date().getTime());
        asynResult.setIdentity(commCheck.getId());
        asynResult.setContent(checkVO);
        LogUtil.info(fourGCheckVO.getId(), "{} 上报4G稽查：{}", upTopic, JSON.toJSONString(asynResult));
        MqttUtil.send(upTopic, asynResult);

    }

    private void executeTempPressure(String topic, String s) {
        if (topic.startsWith("/RU-LRTU-01A")) {
            executeCheck(topic, s);
            return;
        }
        log.info("收到4G温压: {} {}", topic, s);
        FourGTempPressureVO fourGTempPressureVO = FourGTempPressureVO.gene(s);
        CommTemperaturepressure commTempPressure = commTemperaturepressureRepository.findOne(Example.of(CommTemperaturepressure.builder().serial(fourGTempPressureVO.getId()).build())).orElse(null);
        String downTopic = topic.replaceAll("up", "down");
        if (null == commTempPressure) {
            fourGSendService.sendRtcCommand(downTopic);
            return;
        }
        boolean heatingPeriod = DateUtil.heatingPeriod(fourGTempPressureVO.getHot());
        String wakeUpCycle = fourGTempPressureVO.wakeUpCycle(heatingPeriod);
        Integer acquisitionCycle = fourGTempPressureVO.acquisitionCycle(heatingPeriod);
        String uitv1 = fourGTempPressureVO.getUitv1();
        String uitv2 = fourGTempPressureVO.getUitv2();
        Date rtc = DateUtil.noLineFormatToDate(fourGTempPressureVO.getRtc());
        Float bat = fourGTempPressureVO.convertFloat(fourGTempPressureVO.getBat()) * 1000;
        fourGSendService.sendCommand(commTempPressure.getId(), downTopic, heatingPeriod, uitv1, uitv2);

        if (null == fourGTempPressureVO.getSitv1()) {
            TemperaturePressureCurrentData currentData = new TemperaturePressureCurrentData();
            currentData.setSerial(fourGTempPressureVO.getId());
            currentData.setRsrp(fourGTempPressureVO.getRsrp());
            currentData.setWakeUpCycle(wakeUpCycle);
            currentData.setSupplyTemp(fourGTempPressureVO.getFirstFloatFromArrayStr(fourGTempPressureVO.getT1()));
            currentData.setReturnTemp(fourGTempPressureVO.getFirstFloatFromArrayStr(fourGTempPressureVO.getT2()));
            currentData.setSupplyPre(fourGTempPressureVO.getFirstFloatFromArrayStr(fourGTempPressureVO.getP1()) * 1000);
            currentData.setReturnPre(fourGTempPressureVO.getFirstFloatFromArrayStr(fourGTempPressureVO.getP2()) * 1000);
            currentData.setStatus(fourGTempPressureVO.getSta());
            currentData.setBatteryVol(bat);
            currentData.setSignal(fourGTempPressureVO.getCsq());
            currentData.setReadTime(new Date());
            currentData.setPanelDate(rtc);

            AsynResult asynResult = new AsynResult();
            asynResult.setCode(ResultConstants.CODE_200);
            asynResult.setMsg(MqttUtil.successString);
            asynResult.setContent(currentData);
            asynResult.setIdentity(commTempPressure.getId());
            LogUtil.info(fourGTempPressureVO.getId(), "上报4G温压：{}", JSON.toJSONString(asynResult));
            MqttUtil.send(TemperaturePressureCurrentData.TOPIC, asynResult);

        } else {
            String[] t1Arr = fourGTempPressureVO.getFromArrayStr(fourGTempPressureVO.getT1());
            String[] t2Arr = fourGTempPressureVO.getFromArrayStr(fourGTempPressureVO.getT2());
            String[] p1Arr = fourGTempPressureVO.getFromArrayStr(fourGTempPressureVO.getP1());
            String[] p2Arr = fourGTempPressureVO.getFromArrayStr(fourGTempPressureVO.getP2());
            if (t1Arr.length != t2Arr.length) {
                log.error("供回温采集数据不一致 t1Arr: {} t2Arr: {}", t1Arr, t2Arr);
                return;
            }
            for (int i = 0; i < t1Arr.length; i++) {
                Float t1 = fourGTempPressureVO.getFromArrayStr(t1Arr, i);
                Float t2 = fourGTempPressureVO.getFromArrayStr(t2Arr, i);
                Float p1 = fourGTempPressureVO.getFromArrayStr(p1Arr, i);
                Float p2 = fourGTempPressureVO.getFromArrayStr(p2Arr, i);

                TemperaturePressureCurrentData currentData = new TemperaturePressureCurrentData();
                currentData.setSerial(fourGTempPressureVO.getId());
                currentData.setRsrp(fourGTempPressureVO.getRsrp());
                currentData.setWakeUpCycle(wakeUpCycle);
                currentData.setSupplyTemp(t1);
                currentData.setReturnTemp(t2);
                currentData.setSupplyPre(p1 * 1000);
                currentData.setReturnPre(p2 * 1000);
                currentData.setStatus(fourGTempPressureVO.getSta());
                currentData.setBatteryVol(bat);
                currentData.setSignal(fourGTempPressureVO.getCsq());
                currentData.setReadTime(new Date());
                if (null != acquisitionCycle) {
                    currentData.setPanelDate(DateUtil.dateSubtractMinutes(rtc, Long.valueOf((t1Arr.length - i - 1) * acquisitionCycle)));
                }

                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setContent(currentData);
                asynResult.setIdentity(commTempPressure.getId());
                LogUtil.info(fourGTempPressureVO.getId(), "上报4G温压：{}", JSON.toJSONString(asynResult));
                MqttUtil.send(TemperaturePressureCurrentData.TOPIC, asynResult);
            }

        }
    }

    public void executeMeter(String topic, String s) {
        log.debug("收到4G表: {} {}", topic, s);
        FourGMeterVO fourGMeterVO = FourGMeterVO.gene(s);
        String downTopic = topic.replaceAll("up", "down");
        log.debug("表 {} 下发topic: {}", fourGMeterVO.getId(), downTopic);
        CommMeter commMeter = commMeterRepository.findOne(Example.of(CommMeter.builder().serial(fourGMeterVO.getId()).build())).orElse(null);
        if (null == commMeter) {
            // 下发校时
            fourGSendService.sendRtcCommand(downTopic);
            return;
        }
        fourGSendService.sendCommand(commMeter.getId(), downTopic, fourGMeterVO.getRp());
        BigDecimal rsrp = null;
        if (StringUtils.isNotBlank(fourGMeterVO.getRsrp())) {
            rsrp = new BigDecimal(fourGMeterVO.getRsrp()).setScale(2, RoundingMode.HALF_UP);
        }
        BigDecimal batteryVolt = Objects.requireNonNull(DigitalUtil.stringToBigDecimal(fourGMeterVO.getVolt(), 3)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        List<MqttBuildMeterDataVo> dataList = new BuildMeterDecode().heatMeterDecode(fourGMeterVO.getData());
        for (MqttBuildMeterDataVo mqttBuildMeterDataVo : dataList) {
            HotMeterVO hotMeterVO = new HotMeterVO();
            hotMeterVO.setMeterSerial(fourGMeterVO.getId());
            hotMeterVO.setWakeUpCycle(fourGMeterVO.getRp());
            hotMeterVO.setRsrp(String.valueOf(rsrp));
            hotMeterVO.setSignInfo(fourGMeterVO.getCsq());
            hotMeterVO.setBatteryVol(batteryVolt.floatValue());

            hotMeterVO.setReadDate(mqttBuildMeterDataVo.getReadDate());
            hotMeterVO.setMeterDate(mqttBuildMeterDataVo.getMeterDate());
            hotMeterVO.setFlow(mqttBuildMeterDataVo.getFlow());
            hotMeterVO.setPower(DigitalUtil.floatToDecimal(mqttBuildMeterDataVo.getHeat()));
            hotMeterVO.setAccFlow(mqttBuildMeterDataVo.getAccFlow());
            hotMeterVO.setAccHeat(DigitalUtil.floatToDecimal(mqttBuildMeterDataVo.getAccHeat()));
            hotMeterVO.setWorkTime(DigitalUtil.intToDecimal(mqttBuildMeterDataVo.getWorkTime()));
            hotMeterVO.setReturnTemp(DigitalUtil.floatToDecimal(mqttBuildMeterDataVo.getOutTemperature()));
            hotMeterVO.setSupplyTemp(DigitalUtil.floatToDecimal(mqttBuildMeterDataVo.getInTemperature()));
            hotMeterVO.setStatus(mqttBuildMeterDataVo.getMeterStatus());
            hotMeterVO.setFaultCode(RunaEquDataAnalysis.heatMeterFaults(hotMeterVO.getStatus()));

            AsynResult asynResult = new AsynResult();
            asynResult.setCode(ResultConstants.CODE_200);
            asynResult.setMsg(MqttUtil.successString);
            asynResult.setContent(hotMeterVO);
            asynResult.setIdentity(commMeter.getId());
            LogUtil.info(fourGMeterVO.getId(), "上报4G表：{}", JSON.toJSONString(asynResult));
            MqttUtil.send(HotMeterVO.TOPIC, asynResult);
        }


    }

    public static void testTemp() {
        String T = "[20.1,20.2,20.3]";
        String[] tempArr = T.replace("[", "").replace("]", "").split(",");
        int tLen = tempArr.length;
        List<PanelVO> panelList = new ArrayList<>();

        for (int i = tLen - 1; i >= 0; i--) {
            PanelVO panelVO = new PanelVO();
            panelVO.setTemperature(Float.valueOf(tempArr[i]));
            Long minutes = (tLen - i - 1) * 100L;
            panelVO.setReadTime(DateUtil.dateSubtractMinutes(new Date(), minutes));
            panelList.add(panelVO);
        }

        if (CollectionUtil.isNotEmpty(panelList)) {
            AsynResult asynResult = AsynResult.success();
            asynResult.setTimestamp(new Date().getTime());
            asynResult.setContent(panelList);
            System.out.println(JSON.toJSONString(asynResult));
        }
    }

    /**
     * 面板
     * @param json
     */
    public void executePanel(String json) {
        log.debug("4G面板: {}", json);
        FourGPanelVO fourGPanelVO = FourGPanelVO.gene(json);
        String downTopic = "/RU-STC-BT1/" + fourGPanelVO.getId() + "/down";
        // 下发校时
        fourGSendService.sendRtcCommand(downTopic);

        CommPanel commPanel = repositoryService.getCommPanel(fourGPanelVO.getId(), 3);
        if (commPanel == null) {
            log.error("新NB面板编号无此档案" + fourGPanelVO.getId());
            return;
        }
        log.debug("commPanel: {}", JSON.toJSONString(commPanel));
//        boolean heatingPeriod = DateUtil.heatingPeriod(fourGPanelVO.getHot());
//        String wakeUpCycle = fourGPanelVO.wakeUpCycle(heatingPeriod);
//        Integer acquisitionCycle = fourGPanelVO.acquisitionCycle(heatingPeriod);
//        String uitv1 = fourGPanelVO.getUitv1();
//        String uitv2 = fourGPanelVO.getUitv2();
//        Date rtc = DateUtil.noLineFormatToDate(fourGPanelVO.getRtc());
//        Float bat = fourGPanelVO.convertFloat(fourGPanelVO.getBat()) * 1000;
//        fourGSendService.sendCommand(fourGPanelVO.getId(), downTopic, heatingPeriod, uitv1, uitv2);

        // 采样温度
        String[] tempArr = fourGPanelVO.getT1().replace("[", "").replace("]", "").split(",");
        int tLen = tempArr.length;

        // 供暖季采样周期，分钟
        Long sitv1 = Long.valueOf(fourGPanelVO.getSitv1());

        // 最后一次采样时间
        Date lastETime = toNoLineFormatDate(fourGPanelVO.getEtime());

        List<PanelVO> panelList = new ArrayList<>();
        Date now = new Date();
        for (int i = tLen - 1; i >= 0; i--) {
            PanelVO panelVO = new PanelVO();
            panelVO.setSerial(fourGPanelVO.getId());
            panelVO.setSignal(fourGPanelVO.getCsq());
            panelVO.setBatteryVol(toFloat(fourGPanelVO.getBat()));
            panelVO.setTc(fourGPanelVO.getTc());
            panelVO.setRsrp(fourGPanelVO.getRsrp());
            panelVO.setSoftVersion(fourGPanelVO.getVer());
            panelVO.setStatus(fourGPanelVO.getSta());
            panelVO.setFaultCode(fourGPanelVO.faultStr());
//            panelVO.setBatteryVol(bat);
            // 供暖季上报周期
            panelVO.setWakeUpCycle(fourGPanelVO.getUitv1());
            panelVO.setTemperature(Float.valueOf(tempArr[i]));
            Long minutes = (tLen - i - 1) * sitv1;
            panelVO.setReadTime(now);
            panelVO.setPanelDate(DateUtil.dateSubtractMinutes(lastETime, minutes));
            panelList.add(panelVO);
        }

        if (CollectionUtil.isNotEmpty(panelList)) {
            AsynResult asynResult = AsynResult.success();
            asynResult.setTimestamp(new Date().getTime());
            asynResult.setIdentity(commPanel.getId());
            asynResult.setContent(panelList);
            log.debug("asynResult: {}", JSON.toJSONString(asynResult));
            LogUtil.info(fourGPanelVO.getId(), "上报4G面板：{}", JSON.toJSONString(asynResult));
            MqttUtil.send(PanelVO.TOPIC, asynResult);
        }

    }

    private CommValve getCommValve(String serial) {
        CommValve commValve = null;
        try {
            commValve = repositoryService.getCommValveByNodeSerialAndCommunicationType(serial, 3);
        } catch (Exception e) {
            log.error("新NB阀编号 {} 查询报错: ", serial, e);
        }
        return commValve;
    }

    private CommMeter getMeter(String serial) {
        CommMeter commMeter = null;
        try {
            commMeter = repositoryService.getCommMeter(serial, 3);
        } catch (Exception e) {
            log.error("表编号 {} 查询报错: ", serial, e);
        }
        return commMeter;
    }

    /**
     * 阀门
     * @param json
     */
    public void executeValveAndMeter(String topic, String json) {
        FourGValveVO fourGValveVO = FourGValveVO.gene(json);
        executeValve(topic, fourGValveVO);
        executeValveMeter(topic, fourGValveVO);
    }

    public void executeValveMeter(String topic, FourGValveVO fourGValveVO) {
        String mok = fourGValveVO.getMok();
        if (null != mok && "1".equals(mok)) {
            CommMeter meter = getMeter(fourGValveVO.getId());
            if (null == meter) {
                return;
            }
            HotMeterVO hotMeterVO = new HotMeterVO();
            hotMeterVO.setMeterSerial(fourGValveVO.getId());
            hotMeterVO.setReadDate(new Date());
            hotMeterVO.setMeterDate(toNoLineFormatDate(fourGValveVO.getMdt()));
            hotMeterVO.setAccHeat(toFloat(fourGValveVO.getMrl()) * 1000f / 3.6f);
            hotMeterVO.setAccFlow(toFloat(fourGValveVO.getMll()));
            hotMeterVO.setPower(toFloat(fourGValveVO.getMrgl()));
            hotMeterVO.setFlow(toFloat(fourGValveVO.getMlsl()));
            hotMeterVO.setSupplyTemp(toFloat(fourGValveVO.getMt1()));
            hotMeterVO.setReturnTemp(toFloat(fourGValveVO.getMt2()));
            hotMeterVO.setStatus(fourGValveVO.getMst());
            hotMeterVO.setWakeUpCycle(fourGValveVO.wakeUpCycle());
            AsynResult meterResult = AsynResult.success();
            meterResult.setTimestamp(new Date().getTime());
            meterResult.setIdentity(meter.getId());
            meterResult.setContent(hotMeterVO);
            LogUtil.info(fourGValveVO.getId(), "上报4G阀控表：{}", JSON.toJSONString(meterResult));
            MqttUtil.send(HotMeterVO.TOPIC, meterResult);
        }
    }

    public void executeValve(String topic, FourGValveVO fourGValveVO) {
        String downTopic = topic.replaceAll("up", "down");
        log.debug("{} 下发topic: {}", fourGValveVO.getId(), downTopic);
        CommValve commValve = getCommValve(fourGValveVO.getId());
        if (commValve == null) {
            fourGSendService.sendRtcCommand(downTopic);
            log.error("阀编号 {} 无此档案", fourGValveVO.getId());
            return;
        }
        fourGSendService.sendCommand(commValve.getId(), downTopic
                , fourGValveVO.getHot(), fourGValveVO.getUitv1(), fourGValveVO.getUitv2());

        ValveVO valveVO = new ValveVO();
        valveVO.setValveSerial(fourGValveVO.getId());
        valveVO.setSignal(fourGValveVO.getCsq());
//        valveVO.set(fourGValveVO.getIcc());
        valveVO.setActOpen(toFloat(fourGValveVO.getCur()));
        valveVO.setRemoteSet(toFloat(fourGValveVO.getSet()));
        String mok = fourGValveVO.getMok();
        if ("Unit-OneMeterValve".equals(commValve.getModel()) && null != mok && "1".equals(mok)) {
            valveVO.setSupplyTemp(toFloat(fourGValveVO.getMt1()));
            valveVO.setReturnTemp(toFloat(fourGValveVO.getMt2()));
            valveVO.setFlow(toFloat(fourGValveVO.getMlsl()));
        } else {
            valveVO.setSupplyTemp(toTemp(fourGValveVO.getT1()));
            valveVO.setReturnTemp(toTemp(fourGValveVO.getT2()));
        }
        valveVO.setStatus(fourGValveVO.getSta());
        valveVO.setPowerType(analysePowerType(fourGValveVO.getSta()));
//        valveVO.setFaultCode(FourGValveVO.faultStr(fourGValveVO.getSta()));
        valveVO.setSoftVersion(fourGValveVO.getVer());
        valveVO.setLR(fourGValveVO.getMode() == null ? null : fourGValveVO.getMode().equalsIgnoreCase("0") ? ValveVO.LREnum.本地 : ValveVO.LREnum.远程);
        valveVO.setModel(ValveVO.geneModel(Objects.requireNonNull(toInteger(fourGValveVO.getTac()))));
        valveVO.setBatteryVol(toFloat(fourGValveVO.getBat()));
        valveVO.setOpenTime(toFloat(fourGValveVO.getLife()));
        Date date = toNoLineFormatDate(fourGValveVO.getRtc());
        valveVO.setValveDate(date);
        valveVO.setReadTime(new Date());
        valveVO.setRsrp(fourGValveVO.getRsrp());
        valveVO.setWakeUpCycle(fourGValveVO.wakeUpCycle());
        AsynResult asynResult = AsynResult.success();
        asynResult.setTimestamp(new Date().getTime());
        asynResult.setIdentity(commValve.getId());
        asynResult.setContent(valveVO);
        LogUtil.info(fourGValveVO.getId(), "上报4G阀：{}", JSON.toJSONString(asynResult));
        MqttUtil.send(ValveVO.TOPIC, asynResult);
    }

    private Date toNoLineFormatDate(String s) {
        if (StringUtil.isBlank(s)) {
            return null;
        }
        if (s.length() == 12) {
            s = "20" + s;
        }
        return DateUtil.noLineFormatToDate(s);
    }

    public static void main(String[] args) {
        RUEquService ruEquService = new RUEquService();
//        System.out.println(ruEquService.analysePowerType("9980"));
//        System.out.println(ruEquService.toNoLineFormatDate("20240812190809"));
//        testTemp();

    }

    private Integer analysePowerType(String sta) {
        if (StringUtil.isBlank(sta)) {
            return null;
        }
        Integer r = null;
        try {
            r = (Integer.parseInt(sta, 16) >> 11) & 1;
        } catch (Exception e) {
            log.error("analysePowerType: {}", e);
        }
        return r;
    }


    private Float toTemp(String s) {
        if (StringUtil.isBlank(s)) {
            return null;
        }
        String r = s.replace("[", "").replace("]", "");
        if (StringUtil.isBlank(r)) {
            return null;
        }
        String[] split = r.split(",");
        if (null == split || split.length == 0) {
            return null;
        }
        return toFloat(split[0]);
    }

    private Float toFloat(String s) {
        if (StringUtil.isBlank(s)) {
            return null;
        }
        Float r = null;
        try {
            r = Float.valueOf(s);
        } catch (Exception e) {
            log.error("toFloat: {} ", e.getMessage());
        }
        return r;
    }

    private Integer toInteger(String s) {
        if (StringUtil.isBlank(s)) {
            return null;
        }
        Integer r = null;
        try {
            r = Integer.valueOf(s);
        } catch (Exception e) {
            log.error("toInteger: {} ", e.getMessage());
        }
        return r;
    }

}
